<?php

namespace app\api\behavior\order;

use app\common\library\Sfkuaidi;
use app\common\library\sms\Driver as SmsDriver;
use app\common\model\Goods;
use app\common\model\OrderAddress;
use app\common\model\OrderGoods;
use app\common\model\Setting as SettingModel;
use app\common\service\Message as MessageService;
use app\common\service\order\Printer as PrinterService;
use app\common\service\wechat\wow\Order as WowOrder;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\OrderStatus as OrderStatusEnum;
use app\common\enum\order\OrderSource as OrderSourceEnum;
use think\Log;

/**
 * 订单支付成功后扩展类
 * Class PaySuccess
 * @package app\api\behavior\order
 */
class PaySuccess
{
    // 订单信息
    private $order;

    // 订单类型
    private $orderType;

    private $wxappId;

    /**
     * 订单来源回调业务映射类
     * @var array
     */
    protected $sourceCallbackClass = [
        OrderSourceEnum::MASTER => 'app\api\service\master\order\PaySuccess',
        OrderSourceEnum::BARGAIN => 'app\api\service\bargain\order\PaySuccess',
        OrderSourceEnum::SHARP => 'app\api\service\sharp\order\PaySuccess',
    ];

    /**
     * 执行入口
     * @param $order
     * @param int $orderType
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function run($order, $orderType = OrderTypeEnum::MASTER)
    {
        // 设置当前类的属性
        $this->setAttribute($order, $orderType);
        // 订单公共业务
        $this->onCommonEvent();
        // 普通订单业务
        if ($orderType == OrderTypeEnum::MASTER) {
            $this->onMasterEvent();
        }

        // 顺丰自动下单
//        $this->sfSend();

        // 订单来源回调业务
        $this->onSourceCallback();

        return true;
    }

    /**
     * 设置当前类的属性
     * @param $order
     * @param int $orderType
     */
    private function setAttribute($order, $orderType = OrderTypeEnum::MASTER)
    {
        $this->order = $order;
        $this->wxappId = $this->order['wxapp_id'];
        $this->orderType = $orderType;
    }

    /**
     * 订单公共业务
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function onCommonEvent()
    {
        // 发送消息通知
        MessageService::send('order.payment', [
            'order' => $this->order,
            'order_type' => $this->orderType,
        ]);
        // 小票打印
        (new PrinterService)->printTicket($this->order, OrderStatusEnum::ORDER_PAYMENT);

    }

    /**
     * 普通订单业务
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    private function onMasterEvent()
    {
        // 同步好物圈
        (new WowOrder($this->wxappId))->import([$this->order], true);
    }

    /**
     * 订单来源回调业务
     * @return bool
     */
    private function onSourceCallback()
    {
        if (!isset($this->order['order_source'])) {
            return false;
        }
        if (!isset($this->sourceCallbackClass[$this->order['order_source']])) {
            return false;
        }
        $class = $this->sourceCallbackClass[$this->order['order_source']];
        return !is_null($class) ? (new $class)->onPaySuccess($this->order) : false;
    }

    /**
     * 顺丰自动发货
     * @return void
     */
    private function sfSend()
    {
        Log::write('开始下单：'.json_encode($this->order, JSON_UNESCAPED_UNICODE), 'sf-info');
        $order_address = (new OrderAddress())->where('order_id', $this->order->order_id)->find();
        Log::write('地址：'.json_encode($order_address, JSON_UNESCAPED_UNICODE), 'sf-info');
        if ($order_address)
        {
            $goods = OrderGoods::where('order_id', $this->order->order_id)->select();
            if (!$goods){
                Log::write('订单对于的商品不存在 order_id='.$this->order->order_id, 'sf-info');
                return;
            }

            // 获取商品名称和数量
            $goods_name  = '';
            $goods_total = 0;
            foreach ($goods as $val)
            {
                $goods_total = $goods_total + $val['total_num'];
                if ($val['goods_id'] == 1){
                    $goods_name .= "小程序-盛意月饼盒装*{$val['total_num']} ";
                }else if ($val['goods_id'] == 3){
                    $goods_name .= "小程序-盛意月饼《礼盒装》*{$val['total_num']} ";
                }else{
                    $goods_name .= Goods::where('goods_id', $val['goods_id'])->value('goods_name') ;
                    $goods_name .= '*'.$val['total_num'] . ' ';
                }
            }

            $data = [
                'outOrderNo' => $this->order->order_no, //订单号，不能重复
                'senderContact' => '贵州食之有味食品有限公司', //寄件人姓名
                'senderTel' => '085186608499', //寄件人联系⽅方式
                'senderAddress' => '贵州省贵阳市南明区花果园财富广场1622', //寄件人详细地址若省市区不填，则传入完整寄件地址

                'recipientContact' => $order_address['name'], // 收件人姓名
                'recipientTel' => $order_address['phone'], //收件人联系⽅方式,
                'recipientAddress' => $order_address['region']['province'].$order_address['region']['city'].$order_address['region']['region']. $order_address['detail'], // 收件⼈详细地址若省市区不填，则传入完整寄件地址

                'cargo' => [
                    'name'  => $goods_name, // 商品名称
                    'count' => $goods_total, // 商品数量
                ],
                'province' => $order_address['region']['province'],
            ];
            $res_sf = Sfkuaidi::create($data);
            if (is_array($res_sf) && $res_sf['returnCode'] == 'SUCCESS')
            {
                // 顺丰下单成功后，单独修改顺丰运单号
                $this->order->express_no = $res_sf['mailNo'];
                $this->order->save();
                Log::write('下单并修改单号成功，order_id：'.$this->order->order_id.' 快递单号：'.$res_sf['mailNo'], 'sf-info');
            }else{
                Log::write('下单失败，order_id：'.$this->order->order_id, 'sf-info');
                // 判断如果为疫情地区自动取消订单
                if (!empty($res_sf['errorMsg']))
                {
                    $this->smsSendFail($order_address['phone'], $goods_name, $res_sf['errorMsg']);
                    $this->smsSendFail('13308643617', $goods_name, $res_sf['errorMsg']);
                }

            }

        }else{
            Log::write('收货地址不存在-order_id='.$this->order->order_id, 'sf-info');
        }
    }

    /**
     * 发送顺丰下单失败短信
     * @param $accept_phone
     * @param $goods_name
     * @param $desc
     * @return mixed
     * @throws \think\Exception
     */
    private function smsSendFail($accept_phone, $goods_name, $desc)
    {
        $smsConfig = SettingModel::getItem('sms', 10001);
        $msg_type = 'sf_fail';
        $SmsDriver = new SmsDriver([
            'default' => 'aliyun',
            'engine' => [
                'aliyun' => [
                    'AccessKeyId'     => $smsConfig['engine']['aliyun']['AccessKeyId'],
                    'AccessKeySecret' => $smsConfig['engine']['aliyun']['AccessKeySecret'],
                    'sign'            => $smsConfig['engine']['aliyun']['sign'],
                    $msg_type => [
                        'template_code' => 'SMS_249225656',
                        'accept_phone'  => $accept_phone,
                    ],
                ],
            ],
        ]);

        $templateParams = [
            'name' => $goods_name,
            'desc' => $desc
        ];
        if ($SmsDriver->sendSms($msg_type, $templateParams, true)) {
            Log::write('短信发送成功', 'sf-info');
        }else{
            Log::write('短信发送失败', 'sf-info');
        }
    }

}